from json import JSONDecodeError
import requests
from lib.error_log import ErrorLog
from utils.get_encrypt_utils import encrypt_xor_param

log = ErrorLog().get_log()


class HttpCli:
    """请求相关封装类方法"""

    def __init__(self, headers: dict, session=None):
        self.host = ""
        self.headers = headers if headers else {}
        self.body = {}
        self._session = requests.session() if session is None else session

    def get_api_url(self, url: str):
        """获取api的url"""

        if url.startswith("http"):
            #  startswith() 方法用于判断字符串是否以指定前缀开头，如果是则返回 True，否则返回 False。
            return url
        else:
            return self.host + url

    def exec_request(self, method, url, data, allow_redirects=False, **kwargs):
        log.info(FormatRequest.log_request(method, url, self.headers, data, **kwargs))
        response = requests.request(method=method,
                                    url=self.get_api_url(url),
                                    headers=self.headers,
                                    data=data,
                                    allow_redirects=allow_redirects,
                                    **kwargs)
        log.info(FormatRequest.log_response(response))
        print(response.json())
        return response


class FormatRequest:
    """输出格式化的请求,响应日志的模块"""
    str_req = """
----------- 请求的参数---------------
请求-Url:     【{url}】
请求-Method:  【{method}】
请求-Headers: 【{headers}】
请求-Data：    【{data}】
"""

    str_resp = """   
-------------响应的参数-------------
响应-CODE：    【{code}】
响应-HEADERS：【{headers}】
响应-BODY：    【{body}】
    
"""

    @classmethod
    def log_request(cls, method, url, headers, data, **kwargs):
        """日志: 请求时候的请求参数,方法,和具体数据输出"""
        format_request = cls.str_req.format(url=url,
                                            method=method,
                                            headers=headers,
                                            data=data,
                                            **kwargs
                                            )
        if kwargs.get("params"):
            format_request += f"""请求-Params: 【{kwargs.get('params')}】\n"""
        if kwargs.get("json"):
            format_request += f"""请求-Json ： 【{kwargs.get('json')}】\n"""
        return format_request

    @classmethod
    def log_response(cls, response):
        """日志:响应结果内容的输出"""
        try:
            body = response.json()
        except JSONDecodeError:
            body = response.content.decode("utf-8")
        format_response = cls.str_resp.format(code=response.status_code,
                                              body=body,
                                              headers=response.headers)
        return format_response


if __name__ == '__main__':
    url = "https://market.msshuo.cn/ImUserGroup/applyJoinMemberGroup"
    method = "post"
    requests_data = {"groupId": "1888",
                     "mid": "7120939",
                     "applyReply": "9898989"}
    request_data = encrypt_xor_param(requests_data, "market", 2)
    headers = {
        "User-Agent": "User-Agent:X7Market/4.86.999.3359/Android/5.1.1/phone/HUAWEI_YAL-AL10/5f92fec190f31afa551d6f9f10bc8910/fbef5570cea23be99ba155ca2efa4e48X7Market/4.86.999.3359/Android/5.1.1/phone/HUAWEI_YAL-AL10/5f92fec190f31afa551d6f9f10bc8910/fbef5570cea23be99ba155ca2efa4e48",
        "Content-Type": "application/x-www-form-urlencoded",
        "X7DeviceToken": "UFJFSUQuMSNiMDcxNzhkNWY1NzlhZTZhMGU0MDBhNGExNDUxOTk2My1oLTE2NDY5MTI5ODUwMDQtY2E2NjNlNzgzZmE2NDU3N2I1NTNmMGViMDU5YjI2MzEjOGlHMjJLT3hubnBERXpxUURUZlNqczVBS1lNemk4bzNtbDlEclNnNXUvTlVEeFgrdTFHczhHSGJ1dG5PQ2RSdEl2YlpWS2Zsd1owZjFuVVVPUGs2NTB6eE4xVXpyeHh6WUpoNjhpUHBzNHAwZTRxZDhTMDh0aHl6TEZTbkgzNmhXUk9YOGQ5NFVqRWRia2VPbzZIQnFLZEIwb2lKY1hnVDhVaEFvUHY0U29DTFlCMHIwMk9zeGptS0g3TWp3VFFhT2F3RGw1Q3ZiZ2VudVMwTFU3N21rVzNaR1Q5Tnh6Si9Xb0FPUHFUNXBUdUFvOTZrSUZXK0hsVUVTWWp3eWpsZjZtakJYZTloSENESVZCdU52Y1hNUHJvSVFHRjhBNVQxeExTaUFLY2Q3RU9ITzdweCtvY0pPT1JOZVI2aEQ4V3g0VmpUeG92eDhFWTZ5S3dxSy9YQVBJMHBHR0E2Q252RzVxTXdJK3ZkdFFpdm1ZM3ZqbDUwL3BMV24wdzJIakJmUVZBTW9yWnJ5SVJBL2l2RTRybFlUZEhETXJKNU9RdzN1bTVSU1ZiTXdQR2NLUEE2bnV0K3FOMU9yTlBuUkpwOTJjRGpMd1lVVmFpSUJhamhvcytqRnkzYVJWdVZ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oVi81VWEvRFBId0tqUXdqY1J5cVpVRVU2QnRqUjFTR05IL1ZOR0ZyNk5LUFlFRDBjLzBlQlJvQU1KRlh6MTd2RXp1dlRxNGlPMW00Y3ZKNThWMXFqZ244VDlKaWRLbUh4VGxSa29Sd3FlK2srY0tGIzEuMDgx",
    }
    print(FormatRequest().log_request(method=method, url=url,headers=headers, data=request_data))

    # url = "https://market.msshuo.cn/ImUserGroup/applyJoinMemberGroup"
    # method = "post"
    # requests_data = {"groupId": "1888",
    #                  "mid": "7120939",
    #                  "applyReply": "9898989"}
    # headers={
    #     "User-Agent": "User-Agent:X7Market/4.86.999.3359/Android/5.1.1/phone/HUAWEI_YAL-AL10/5f92fec190f31afa551d6f9f10bc8910/fbef5570cea23be99ba155ca2efa4e48X7Market/4.86.999.3359/Android/5.1.1/phone/HUAWEI_YAL-AL10/5f92fec190f31afa551d6f9f10bc8910/fbef5570cea23be99ba155ca2efa4e48",
    #     "Content-Type": "application/x-www-form-urlencoded",
    #     "X7DeviceToken": "UFJFSUQuMSNiMDcxNzhkNWY1NzlhZTZhMGU0MDBhNGExNDUxOTk2My1oLTE2NDY5MTI5ODUwMDQtY2E2NjNlNzgzZmE2NDU3N2I1NTNmMGViMDU5YjI2MzEjOGlHMjJLT3hubnBERXpxUURUZlNqczVBS1lNemk4bzNtbDlEclNnNXUvTlVEeFgrdTFHczhHSGJ1dG5PQ2RSdEl2YlpWS2Zsd1owZjFuVVVPUGs2NTB6eE4xVXpyeHh6WUpoNjhpUHBzNHAwZTRxZDhTMDh0aHl6TEZTbkgzNmhXUk9YOGQ5NFVqRWRia2VPbzZIQnFLZEIwb2lKY1hnVDhVaEFvUHY0U29DTFlCMHIwMk9zeGptS0g3TWp3VFFhT2F3RGw1Q3ZiZ2VudVMwTFU3N21rVzNaR1Q5Tnh6Si9Xb0FPUHFUNXBUdUFvOTZrSUZXK0hsVUVTWWp3eWpsZjZtakJYZTloSENESVZCdU52Y1hNUHJvSVFHRjhBNVQxeExTaUFLY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5d052b24zVWI3NFlIdVVENzRrazBydUpDQUNVdzBUOVFJaGhNdnMwaVpLZ0djdEZWbDU2RFcvREl4Z3BqNUpaT1RNZ3FaZm92MHFmRm94cXc0bDNEME4rSkh5Tk5xL1pTV3h3dEhvRFZrSWljN01wcnBGclNjR2pUKytrNlNaQUdiTEliTURnbGN1T21jbEFCaVZPdlR0TW05c2JQVmNWdDNnaVlnbjFyeXZEY29vLzVvakpYbGJ0Qzdkb1NoNXBoVi81VWEvRFBId0tqUXdqY1J5cVpVRVU2QnRqUjFTR05IL1ZOR0ZyNk5LUFlFRDBjLzBlQlJvQU1KRlh6MTd2RXp1dlRxNGlPMW00Y3ZKNThWMXFqZ244VDlKaWRLbUh4VGxSa29Sd3FlK2srY0tGIzEuMDgx",
    #     "x7sy-dev": "oaid=&imei=865166029466953&new_uuid=fbef5570cea23be99ba155ca2efa4e48&uuid=5f92fec190f31afa551d6f9f10bc8910&is_simulator=1&idfa=fbef5570cea23be99ba155ca2efa4e48&temp_idfa=-1&tgid=1&sign=2b2ddca447c1610b67be6951dc208fbe&ua=Mozilla/5.0 (Linux; Android 5.1.1; YAL-AL10 Build/LMY49I; wv) AppleWebKit/537.36 (KHTML, like Gecko) Version/4.0 Chrome/52.0.2743.100 Mobile Safari/537.36"
    #
    # }
    # request_data = encrypt_xor_param(requests_data, "market", 2)
    # print(HttpCli(headers=headers).exec_request(method=method, url=url, data=requests_data))
